package com.person.jc.web.base.notice;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.person.jc.service.base.notice.BdNoticeService;
import com.person.jc.utils.DateUtils;
import com.person.jc.utils.Servlets;
import com.person.jc.utils.Utils;

public class BdNoticeController extends Controller {
	
	public void init(){
		setAttr("menuId", getPara("menuId"));
		setAttr("startDate",DateUtils.formatDate(DateUtils.addDays(new Date(), -14), "yyyy-MM-dd"));
		setAttr("endDate",DateUtils.getDate());
		render("main.jsp");
	}
	
	public void list(){
		Map<String,Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
		List<Record> list = BdNoticeService.me.getList(map);
		setAttr("list", list);
		render("list.jsp");
	}
	
	public void edit(){
		String id = getPara("noticeId");
		String view = getPara("view");
		setAttr("now", DateUtils.getDateTime());
		if(Utils.isNotEmpty(id)){
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("noticeId", id);
			List<Record> list = BdNoticeService.me.getList(map);
			if(list.size() != 0){
				setAttr("obj", list.get(0));
			}
		}
		List<Record> users = BdNoticeService.me.getUserList(id, view);
		setAttr("userList", users);
		setAttr("view", view);
		render("edit.jsp");
	}
	
	@Before(Tx.class)
	public void save(){
		String res = "success";
		Map<String,Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
		String[] userIds = getParaValues("userId");
		String noticeId = String.valueOf(map.get("noticeId"));
		if(Utils.isNotEmpty(noticeId)){
			BdNoticeService.me.update(map);
		}else{
			noticeId = BdNoticeService.me.save(map);
		}
		BdNoticeService.me.removeUsers(noticeId);
		String noticeUser = String.valueOf(map.get("noticeUser"));
		if("2".equals(noticeUser)){
			BdNoticeService.me.saveUsers(noticeId, userIds);
		}
		renderText(res);
	}
	
	public void delete(){
		String res = "success";
		String noticeIds = getPara("noticeIds");
		try {
			for (String noticeId : noticeIds.split(",")) {
				BdNoticeService.me.delete(noticeId);
				BdNoticeService.me.removeUsers(noticeId);
			}
		} catch (Exception e) {
			e.printStackTrace();
			res = "error";
		}
		renderText(res);
	}
}
